package com.androidhuman.example.mapsv2example;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ReportActivity extends FragmentActivity {
	int N=1;
	String text;
	String detail;
	private static final int CAPTURE_IMAGE_CAPTURE_CODE = 0;
	private static final int REQUEST_GALLERY_IMAGE_CODE = 1;

	Intent i;
	ImageView pic;
	ImageView pic2;

	Bitmap resized = null;

	View report_camera;
	View report_gallery;

	GPSTracker gps;
	View btnShowLocation;

	TextView rAddressView;
	EditText rTitleView;
	EditText rDetailAddressView;
	EditText rTextView;

	SharedPreferences userPrefs;
	SharedPreferences.Editor userPrefsEditor;
	String mylocation;

	String report_title;
	String report_address;
	String report_detail_address;
	String report_text;
	int report_icon;

	String imagepath;
	String Photoname;

	int imagecheck = 0;
	int event_id=0;
	boolean isFromEvent=false;
	int userinfo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report);
		
		Intent intent = getIntent();
		isFromEvent = intent.getBooleanExtra("isFromEvent", false);
		event_id=intent.getIntExtra("eventID", 0);
		
		//Toast.makeText(getApplicationContext(), Integer.toString(event_id), Toast.LENGTH_SHORT).show();;
		
		pic = (ImageView) findViewById(R.id.pic1);
		pic2 = (ImageView) findViewById(R.id.pic2);

		userPrefs = getSharedPreferences("USER", MODE_PRIVATE);
		userPrefsEditor = userPrefs.edit();
		mylocation = userPrefs.getString("mylocation", "업데이트 되지 않음");
		userinfo = userPrefs.getInt("myid", 0);

		resized = null;

		report_camera = (View) findViewById(R.id.report_camera);
		report_gallery = (View) findViewById(R.id.report_gallery);

		btnShowLocation = (View) findViewById(R.id.btn_report_loca);

		rAddressView = (TextView) findViewById(R.id.report_address);
		rAddressView.setText(mylocation);

		rTitleView = (EditText) findViewById(R.id.report_title);
		rTextView = (EditText) findViewById(R.id.report_text);
		rDetailAddressView = (EditText) findViewById(R.id.report_detail_address);

		Button makereport_close = (Button) findViewById(R.id.makebanner_close);

		makereport_close.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {

				article_insert();

				// ipm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
				// 0);
			}
		});

		report_camera.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {

				Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(i, CAPTURE_IMAGE_CAPTURE_CODE);

			}
		});

		report_gallery.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {

				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Complete action using"),
						1);

			}
		});

		btnShowLocation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// create class object
				gps = new GPSTracker(ReportActivity.this);
				Log.i("Socialism", "OK0");
				// check if GPS enabled
				if (gps.canGetLocation()) {

					double latitude = gps.getLatitude();
					double longitude = gps.getLongitude();

					// \n is for new line
					Toast.makeText(
							getApplicationContext(),
							"현재 위치 - \n위도: " + latitude
							+ "\n경도: " + longitude, Toast.LENGTH_LONG)
							.show();

					userPrefsEditor.putFloat("mylatitude", (float)latitude); 
					userPrefsEditor.putFloat("mylongitude", (float)longitude); 

					// Toast.makeText(getApplicationContext(),
					// gps.address,
					// Toast.LENGTH_LONG).show();
					// Log.i("Socialism","OK0");

					if (gps.getAddress(latitude, longitude) == null) {
						rAddressView.setText("업데이트 되지 않음");
					} else {
						rAddressView.setText(gps
								.getAddress(latitude, longitude));
					}

				} else {
					// can't get location
					// GPS or Network is not enabled
					// Ask user to enable GPS/network in settings
					gps.showSettingsAlert();
				}

				// gps.getAddress();

				mylocation = rAddressView.getText().toString();

				userPrefsEditor.putString("mylocation", mylocation);
				userPrefsEditor.commit();

			}
		});

	}

	public void article_insert(int event_id) {
		report_title=rTitleView.getText().toString();
		report_text=rTextView.getText().toString();
		report_detail_address=rDetailAddressView.getText().toString();



		String strArticle_id=HttpRequest.get(
				"http://dev.ts.hs.kr/trend/reporters_make_articles.php", true, 
				"latitude" , GPSTracker.latitude,
				"longitude", GPSTracker.longitude,
				"title", report_title,
				"text", report_text,
				"event_id", event_id,
				"user_id", userinfo,
				"address", mylocation,//report_address,
				"detail_address", report_detail_address
				).body();
		if(strArticle_id!=null && strArticle_id!=""){
			Toast toast1=Toast.makeText(getBaseContext(), "글이 작성되었습니다.",
					Toast.LENGTH_LONG);
			toast1.show();}

		String stringArticle_id="";
		String temp="";
		for(int i=0; i<strArticle_id.length(); i++)
		{
			temp=strArticle_id.substring(i, i+1);
			if(temp.charAt(0)>47 && temp.charAt(0)<58)
			{stringArticle_id+=temp;}
		}

		int article_id=Integer.parseInt(stringArticle_id);

		Photoname = "1_" + stringArticle_id+"_";		//프로필사진:0 기사:1 이벤:2
		if (imagecheck == 1) {


			File imageFile = new File(imagepath);
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize=1;
			Bitmap bitmap = BitmapFactory.decodeFile(imagepath,options);
			String fileName = Uri.parse(imagepath).getLastPathSegment();
			
//			imagepath= getBaseContext().getCacheDir()+fileName;
//			SaveBitmapToFileCache(bitmap, imagepath, 1);
//			long L = imageFile.length();
//			for(;(L/(2*2))>2097152l; )
//			{
//				options = new BitmapFactory.Options();
//				options.inSampleSize=2;
//				bitmap = BitmapFactory.decodeFile(imagepath,options);
//				SaveBitmapToFileCache(bitmap, imagepath, 1);
//				imageFile = new File(imagepath);
//				L = imageFile.length();
//			}

			RequestParams params = new RequestParams();
			params.put("title", Photoname);

			try {
				params.put("image", imageFile);
			} catch (Exception e) {
				// Log.i("1", "oh no");
			}

			AsyncHttpClient client = new AsyncHttpClient();
			client.post("http://dev.ts.hs.kr/trend/phototemp.php", params,
					new AsyncHttpResponseHandler() {
				public void onSuccess(String response) {
					Log.w("async", response);
					setResult(RESULT_OK, new Intent());

				}
			});

		}
		String picUpload=HttpRequest.get(
				"http://dev.ts.hs.kr/trend/reporters_photo_linker.php", true, 
				"id" , article_id,
				"type", 1
				).body();
		if(picUpload.compareTo("SUCCESS")==0)
		{Toast toast1=Toast.makeText(getBaseContext(), "글이 작성되었습니다.",
				Toast.LENGTH_LONG);
		toast1.show();}

		this.finish();

	}
	public void article_insert()
	{
		if(!isFromEvent)
			article_insert(-1);
		else
			article_insert(event_id);
	}

	@SuppressWarnings("null")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK && data != null) {

			Uri selectedImageUri = data.getData();
			imagepath = getPath(selectedImageUri);

			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize=10;
			Bitmap bitmap = BitmapFactory.decodeFile(imagepath,options);

			String fileName = Uri.parse(imagepath).getLastPathSegment();

			//SaveBitmapToFileCache(bitmap, getBaseContext().getCacheDir()+fileName);
			
			//imagepath= getBaseContext().getCacheDir()+fileName;
			SaveBitmapToFileCache(bitmap, imagepath, 100);
			
//			File imageFile = new File(imagepath);
//			long L = imageFile.length();
//			int cnt=0;
//			for(;(L/(2*2))>2097152l; )
//			{
//				options.inSampleSize=2;
//				bitmap = BitmapFactory.decodeFile(imagepath,options);
//				SaveBitmapToFileCache(bitmap, imagepath, 2);
//				imageFile = new File(imagepath);
//				L = imageFile.length();cnt++;
//			}
//			Toast toast=Toast.makeText(getBaseContext(), "LL", Toast.LENGTH_SHORT);
//			toast.show();
			
			//Context.getCacheDir()
			resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);

			pic.setVisibility(View.VISIBLE);
			pic.setImageBitmap(resized);

			imagecheck = 1;

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}

	private class CData {
		private String Title;
		private String Text;
		private int Img;
		private int Photo;

		public CData(Context context, int mPhoto, String mTitle, String mText,
				int mImg) {
			Photo = mPhoto;
			Title = mTitle;
			Text = mText;
			Img = mImg;
		}

		public CData(Context context, int mPhoto, String mTitle, String mText) {
			Photo = mPhoto;
			Title = mTitle;
			Text = mText;
			Img = 123456;

		}

		public String getTitle() {
			return Title;
		}

		public String getText() {
			return Text;
		}

		public int getImg() {
			return Img;
		}

		public int getPhoto() {
			return Photo;
		}
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	private void SaveBitmapToFileCache(Bitmap bitmap, String strFilePath, int N) {

		File fileCacheItem = new File(strFilePath);
		OutputStream out = null;

		try
		{
			fileCacheItem.createNewFile();
			out = new FileOutputStream(fileCacheItem);

			bitmap.compress(CompressFormat.JPEG, N, out);
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				out.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}




}